package cn.wh.pet.service.impl;

import cn.wh.basic.exception.BusinessException;
import cn.wh.basic.service.impl.BaseServiceImpl;
import cn.wh.basic.util.BaiduAuditUtils;
import cn.wh.basic.util.CodeGenerateUtils;
import cn.wh.basic.util.DistanceUtil;
import cn.wh.basic.util.Point;
import cn.wh.org.domain.Details;
import cn.wh.org.domain.Shop;
import cn.wh.org.mapper.ShopMapper;
import cn.wh.pet.domain.OrderPetAcquisition;
import cn.wh.pet.domain.Pet;
import cn.wh.pet.domain.SearchMasterMsg;
import cn.wh.pet.domain.SearchMasterMsgAuditLog;
import cn.wh.pet.dto.HandleMsgDto;
import cn.wh.pet.mapper.OrderPetAcquisitionMapper;
import cn.wh.pet.mapper.PetMapper;
import cn.wh.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.wh.pet.mapper.SearchMasterMsgMapper;
import cn.wh.pet.service.ISearchMasterMsgService;
import cn.wh.user.domain.Logininfo;
import cn.wh.user.domain.User;
import cn.wh.user.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yaosang
 * @since 2022-06-28
 */
@Service
@Slf4j
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;

    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    @Autowired
    private PetMapper petMapper;

    /**
     * 发布寻主消息
     * @param smg
     * @param logininfo
     */
    @Override
    public void publish(SearchMasterMsg smg, Logininfo logininfo) {
        //获取当前发布人的信息
        User user = userMapper.loadByLoginIn(logininfo.getId());
        //一：保存寻主消息
        smg.setUserId(user.getId());
        searchMasterMsgMapper.save(smg);
        //二：审核
        //1.系统自动审核
        String str = smg.getTitle() + smg.getName() + smg.getCoatColor() + smg.getAddress();
        if (!BaiduAuditUtils.TextCensor(str)){
            //1.2 审核不通过--给他一次修改再次提交审核的机会 记录审核日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(smg.getId());
            log.setNote("\"审核失败，存在敏感信息，可能是：标题、名字、毛色、地址等！\"");
            searchMasterMsgAuditLogMapper.save(log);
            //@TODO 发送审核失败邮件，提醒客人重新修改并提交审核
            SimpleMailMessage message = new SimpleMailMessage();
            //设置发送人
            message.setFrom("364190601@qq.com");
            //邮件主题
            message.setSubject("驳回通知");
            //邮件内容
            message.setText(log.getNote());
            //收件人
            message.setTo("364190601@qq.com");

            javaMailSender.send(message);
            smg.setState(-1);
        }else{
            smg.setState(1);
            //1.1 审核通过--需要寻找最近的店铺（50公里范围内）
            //.找出发布寻找消息的人的点
            Point point = DistanceUtil.getPoint(smg.getAddress());
            //.从所有门店中，找到这个点最近的门，50公里范围内的
            Shop nearestShop = DistanceUtil.getNearestShop(point, shopMapper.loadAll());
            if (nearestShop != null){
                // 1.1.1 找到了，寻主消息绑定shopId，建议给店铺老板发个消息了，出来接客
                smg.setShopId(nearestShop.getId());
                //给老板发短信
                //SmsUtils.sendSms(phone,"亲，您的验证码是："。请在3分钟内使用！！");
                System.out.println("老板你来订单了");
                log.info("亲爱的老板：{}，你的店铺收到新的信息，请赶快出来接客！！", nearestShop.getName());
            }
        }
        searchMasterMsgMapper.update(smg);
    }

    /**
     * 寻主消息接单
     * @param dto
     */
    @Override
    public void accept(HandleMsgDto dto) {
        //需要先判断是否曾今被别人接单  根据msgId查询收购订单，还要判断状态是否是取消
        // 状态不是取消 + msgId
        OrderPetAcquisition order = orderPetAcquisitionMapper.loadByMsgIdAndNotCancel(dto.getMsgId());
        if (order != null){
            throw new BusinessException("下次搞快点,这已经被抢了");
        }
        //查询订单详情
        SearchMasterMsg msg = searchMasterMsgMapper.loadById(dto.getMsgId());
        //生成宠物
        Pet pet = initPet(dto,msg);
        //保存
        petMapper.save(pet);
        //生成订单
        order = initOrder(dto, msg, pet);
        //保存
        orderPetAcquisitionMapper.save(order);
    }

    /**
     * 拒单
     * @param id
     */
    @Override
    public void reject(Long id) {
        //获取发布信息
        SearchMasterMsg msg = searchMasterMsgMapper.loadById(id);
        msg.setShopId(null);
        searchMasterMsgMapper.update(msg);

        //@TODO  记录拒绝原因
    }

    /**
     * 设置订单基本数据
     * @param dto
     * @param msg
     * @param pet
     * @return
     */
    private OrderPetAcquisition initOrder(HandleMsgDto dto, SearchMasterMsg msg, Pet pet) {
        OrderPetAcquisition order;
        order = new OrderPetAcquisition();
        order.setOrderSn(CodeGenerateUtils.generateOrderSn(dto.getHandler()));
        order.setDigest(pet.getName() + ":收购订单");
        order.setLastcomfirmtime(new Date(System.currentTimeMillis() + 2*24*60*60*1000));
        order.setPetId(pet.getId());
        order.setUserId(msg.getUserId());
        order.setShopId(msg.getShopId());
        order.setAddress(msg.getAddress());
        //3.绑定收购人
        order.setEmpId(dto.getHandler());
        order.setSearchMasterMsgId(msg.getId());
        return order;
    }

    /**
     * 设置宠物基本信息
     * @param dto
     * @param msg
     * @return
     */
    private Pet initPet(HandleMsgDto dto, SearchMasterMsg msg) {
        Pet pet = new Pet();
        pet.setName(msg.getName());
        //@TODO 在收购宠物回来之后，确认订单时，来填写成本价，上架之前来填写售价 包括补充不要宠物信息
        pet.setTypeId(msg.getPetType());
        pet.setShopId(msg.getShopId());
        pet.setSearchMasterMsgId(msg.getId());
        return pet;
    }
}
